package com.kxxnzstdsw.utils

import com.auth0.jwk.JwkProvider
import com.auth0.jwk.JwkProviderBuilder
import com.auth0.jwt.JWT
import com.auth0.jwt.algorithms.Algorithm
import com.kxxnzstdsw.config.JwtConfig
import org.koin.core.Koin
import java.security.KeyFactory
import java.security.interfaces.RSAPrivateKey
import java.security.interfaces.RSAPublicKey
import java.security.spec.PKCS8EncodedKeySpec
import java.util.*
import java.util.concurrent.TimeUnit

val JwtConfig.jwkProvider: JwkProvider
  get() = JwkProviderBuilder(issuer)
    .cached(10, 24, TimeUnit.HOURS)
    .rateLimited(10, 1, TimeUnit.MINUTES)
    .build()

fun JwtConfig.token(koin: Koin, username: String, accountId: String): String {
  val publicKey = koin.get<JwkProvider>().get(kid).publicKey
  val keySpecPKCS8 = PKCS8EncodedKeySpec(Base64.getDecoder().decode(privateKey))
  val privateKey = KeyFactory.getInstance("RSA").generatePrivate(keySpecPKCS8)
  val token = JWT.create()
//    .withAudience(audience)
//    .withIssuer(issuer)
//    需要什么往里放什么但是别放太长
    .withClaim("username", username)
    .withClaim("accountId", accountId)
    .withExpiresAt(Date(System.currentTimeMillis() + 60000))
    .sign(Algorithm.RSA256(publicKey as RSAPublicKey, privateKey as RSAPrivateKey))
  return token
}
